<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>电子礼金系统 - H5应用</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="/socket.io/socket.io.js"></script>
    <style>
        .gradient-bg {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .card-shadow {
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }
        .floating-animation {
            animation: float 3s ease-in-out infinite;
        }
        @keyframes float {
            0%, 100% { transform: translateY(0px); }
            50% { transform: translateY(-10px); }
        }
        .slide-in {
            animation: slideIn 0.5s ease-out;
        }
        @keyframes slideIn {
            from { transform: translateX(-100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <!-- 登录页面 -->
    <div id="login-page" class="min-h-screen gradient-bg flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl p-8 w-full max-w-md card-shadow">
            <div class="text-center mb-8">
                <h1 class="text-3xl font-bold text-gray-800 mb-2">电子礼金系统</h1>
                <p class="text-gray-600">安全便捷的礼金管理</p>
            </div>
            
            <form id="login-form" class="space-y-6">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">用户名</label>
                    <input type="text" id="username" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入用户名" required>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">密码</label>
                    <input type="password" id="password" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入密码" required>
                </div>
                
                <button type="submit" class="w-full bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700 transition duration-200 font-medium">
                    登录
                </button>
                
                <div class="text-center">
                    <button type="button" id="show-register" class="text-blue-600 hover:text-blue-800 text-sm">
                        还没有账号？立即注册
                    </button>
                </div>
            </form>
            
            <form id="register-form" class="space-y-6 hidden">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">用户名</label>
                    <input type="text" id="reg-username" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入用户名" required>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">密码</label>
                    <input type="password" id="reg-password" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入密码" required>
                </div>
                
                <button type="submit" class="w-full bg-green-600 text-white py-3 rounded-lg hover:bg-green-700 transition duration-200 font-medium">
                    注册
                </button>
                
                <div class="text-center">
                    <button type="button" id="show-login" class="text-blue-600 hover:text-blue-800 text-sm">
                        已有账号？立即登录
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- 主应用页面 -->
    <div id="main-app" class="hidden">
        <!-- 顶部导航 -->
        <nav class="bg-white shadow-sm border-b">
            <div class="max-w-7xl mx-auto px-4 py-4">
                <div class="flex justify-between items-center">
                    <div class="flex items-center space-x-4">
                        <h1 class="text-xl font-bold text-gray-800">电子礼金</h1>
                        <select id="event-select" class="px-3 py-1 border border-gray-300 rounded-lg text-sm">
                            <option value="">选择活动</option>
                        </select>
                    </div>
                    <div class="flex items-center space-x-4">
                        <span id="user-info" class="text-sm text-gray-600"></span>
                        <button id="logout-btn" class="text-red-600 hover:text-red-800 text-sm">退出</button>
                    </div>
                </div>
            </div>
        </nav>

        <div class="max-w-7xl mx-auto px-4 py-6">
            <!-- 创建活动按钮 -->
            <div class="mb-6">
                <button id="create-event-btn" class="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition duration-200 font-medium">
                    + 创建新活动
                </button>
            </div>

            <!-- 活动列表 -->
            <div id="events-list" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
                <!-- 活动卡片将通过JavaScript动态生成 -->
            </div>

            <!-- 礼金录入区域 -->
            <div id="gift-section" class="hidden">
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    <!-- 礼金录入表单 -->
                    <div class="bg-white rounded-xl p-6 card-shadow">
                        <h2 class="text-xl font-bold mb-4 text-gray-800">礼金录入</h2>
                        <form id="gift-form" class="space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">姓名</label>
                                <input type="text" id="gift-name" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入姓名" required>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">金额</label>
                                <input type="number" id="gift-amount" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入金额" step="0.01" required>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">支付方式</label>
                                <select id="gift-payment" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                    <option value="现金">现金</option>
                                    <option value="微信">微信</option>
                                    <option value="支付宝">支付宝</option>
                                    <option value="银行卡">银行卡</option>
                                </select>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">备注</label>
                                <textarea id="gift-note" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" rows="3" placeholder="可选"></textarea>
                            </div>
                            
                            <button type="submit" class="w-full bg-red-600 text-white py-3 rounded-lg hover:bg-red-700 transition duration-200 font-medium">
                                确认录入
                            </button>
                        </form>
                        
                        <!-- 多媒体上传区域 -->
                        <div class="mt-6 pt-6 border-t border-gray-200">
                            <h3 class="text-lg font-bold text-gray-800 mb-4">上传多媒体</h3>
                            <form id="media-upload-form" class="space-y-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">文件类型</label>
                                    <select id="media-type" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                        <option value="image">图片</option>
                                        <option value="video">视频</option>
                                        <option value="audio">音频</option>
                                    </select>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">标题</label>
                                    <input type="text" id="media-title" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入标题" required>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">选择文件</label>
                                    <input type="file" id="media-file" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" accept="image/*,video/*,audio/*" required>
                                </div>
                                
                                <button type="submit" class="w-full bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700 transition duration-200 font-medium">
                                    上传文件
                                </button>
                            </form>
                        </div>
                        </form>
                    </div>

                    <!-- 礼金统计 -->
                    <div class="lg:col-span-2 bg-white rounded-xl p-6 card-shadow">
                        <div class="flex justify-between items-center mb-6">
                            <h2 class="text-xl font-bold text-gray-800">礼金统计</h2>
                            <div class="text-right">
                                <div class="text-sm text-gray-600">总金额</div>
                                <div id="total-amount" class="text-3xl font-bold text-red-600">¥0</div>
                                <div class="text-sm text-gray-600 mt-1">总人数: <span id="total-count">0</span></div>
                            </div>
                        </div>
                        
                        <!-- 礼金记录列表 -->
                        <div id="gifts-list" class="max-h-96 overflow-y-auto">
                            <div class="text-center text-gray-400 py-8">
                                <div class="text-4xl mb-2">📝</div>
                                <p>暂无礼金记录</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 创建活动模态框 -->
    <div id="create-event-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
        <div class="bg-white rounded-xl p-6 w-full max-w-md">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-xl font-bold text-gray-800">创建新活动</h3>
                <button id="close-modal" class="text-gray-400 hover:text-gray-600 text-2xl">&times;</button>
            </div>
            
            <form id="create-event-form" class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">活动标题</label>
                    <input type="text" id="event-title" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="如：张三李四婚礼" required>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">活动描述</label>
                    <textarea id="event-description" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" rows="3" placeholder="活动描述（可选）"></textarea>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">活动日期</label>
                    <input type="date" id="event-date" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">主题风格</label>
                    <select id="event-theme" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        <option value="red">喜庆红</option>
                        <option value="gray">肃穆灰</option>
                        <option value="blue">商务蓝</option>
                    </select>
                </div>
                
                <div class="flex space-x-4">
                    <button type="button" id="cancel-create" class="flex-1 px-4 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition duration-200">
                        取消
                    </button>
                    <button type="submit" class="flex-1 px-4 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-200">
                        创建
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // 全局变量
        let currentUser = null;
        let currentEvent = null;
        let socket = null;
        let events = [];

        // API基础URL
        const API_BASE = '/api';

        // 工具函数
        function showMessage(message, type = 'info') {
            const colors = {
                success: 'bg-green-500',
                error: 'bg-red-500',
                info: 'bg-blue-500'
            };
            
            const messageEl = document.createElement('div');
            messageEl.className = `fixed top-4 right-4 ${colors[type]} text-white px-6 py-3 rounded-lg shadow-lg z-50 slide-in`;
            messageEl.textContent = message;
            document.body.appendChild(messageEl);
            
            setTimeout(() => {
                messageEl.remove();
            }, 3000);
        }

        function formatCurrency(amount) {
            return '¥' + parseFloat(amount).toFixed(2);
        }

        function formatDate(dateString) {
            return new Date(dateString).toLocaleDateString('zh-CN');
        }

        // API调用函数
        async function apiCall(endpoint, options = {}) {
            const token = localStorage.getItem('token');
            const config = {
                headers: {
                    'Content-Type': 'application/json',
                    ...(token && { 'Authorization': `Bearer ${token}` })
                },
                ...options
            };

            try {
                const response = await fetch(API_BASE + endpoint, config);
                const data = await response.json();
                
                if (!response.ok) {
                    throw new Error(data.error || '请求失败');
                }
                
                return data;
            } catch (error) {
                console.error('API调用失败:', error);
                throw error;
            }
        }

        // 认证相关
        async function login(username, password) {
            try {
                const data = await apiCall('/auth/login', {
                    method: 'POST',
                    body: JSON.stringify({ username, password })
                });
                
                localStorage.setItem('token', data.token);
                localStorage.setItem('user', JSON.stringify(data.user));
                currentUser = data.user;
                
                showMessage('登录成功', 'success');
                showMainApp();
                loadEvents();
            } catch (error) {
                showMessage(error.message, 'error');
            }
        }

        async function register(username, password) {
            try {
                const data = await apiCall('/auth/register', {
                    method: 'POST',
                    body: JSON.stringify({ username, password })
                });
                
                localStorage.setItem('token', data.token);
                localStorage.setItem('user', JSON.stringify(data.user));
                currentUser = data.user;
                
                showMessage('注册成功', 'success');
                showMainApp();
                loadEvents();
            } catch (error) {
                showMessage(error.message, 'error');
            }
        }

        function logout() {
            localStorage.removeItem('token');
            localStorage.removeItem('user');
            currentUser = null;
            currentEvent = null;
            
            if (socket) {
                socket.disconnect();
                socket = null;
            }
            
            showLoginPage();
        }

        // 页面切换
        function showLoginPage() {
            document.getElementById('login-page').classList.remove('hidden');
            document.getElementById('main-app').classList.add('hidden');
        }

        function showMainApp() {
            document.getElementById('login-page').classList.add('hidden');
            document.getElementById('main-app').classList.remove('hidden');
            
            const user = JSON.parse(localStorage.getItem('user') || '{}');
            document.getElementById('user-info').textContent = `欢迎，${user.username}`;
        }

        // 活动管理
        async function loadEvents() {
            try {
                events = await apiCall('/events');
                renderEvents();
                updateEventSelect();
            } catch (error) {
                showMessage('加载活动列表失败', 'error');
            }
        }

        function renderEvents() {
            const container = document.getElementById('events-list');
            
            if (events.length === 0) {
                container.innerHTML = `
                    <div class="col-span-full text-center py-12">
                        <div class="text-6xl mb-4">🎉</div>
                        <h3 class="text-xl font-medium text-gray-600 mb-2">还没有活动</h3>
                        <p class="text-gray-500">点击上方按钮创建您的第一个活动</p>
                    </div>
                `;
                return;
            }

            container.innerHTML = events.map(event => `
                <div class="bg-white rounded-xl p-6 card-shadow hover:shadow-lg transition duration-200 cursor-pointer" onclick="selectEvent('${event.id}')">
                    <div class="flex justify-between items-start mb-4">
                        <h3 class="text-lg font-bold text-gray-800">${event.title}</h3>
                        <span class="px-2 py-1 text-xs rounded-full ${event.status === 'active' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'}">
                            ${event.status === 'active' ? '进行中' : '已结束'}
                        </span>
                    </div>
                    
                    <p class="text-gray-600 text-sm mb-3">${event.description || '暂无描述'}</p>
                    
                    <div class="flex justify-between items-center text-sm text-gray-500">
                        <span>📅 ${formatDate(event.event_date)}</span>
                        <span>🎨 ${event.theme === 'red' ? '喜庆红' : event.theme === 'gray' ? '肃穆灰' : '商务蓝'}</span>
                    </div>
                </div>
            `).join('');
        }

        function updateEventSelect() {
            const select = document.getElementById('event-select');
            select.innerHTML = '<option value="">选择活动</option>' + 
                events.map(event => `<option value="${event.id}">${event.title}</option>`).join('');
        }

        async function createEvent(eventData) {
            try {
                const data = await apiCall('/events', {
                    method: 'POST',
                    body: JSON.stringify(eventData)
                });
                
                showMessage('活动创建成功', 'success');
                closeCreateEventModal();
                loadEvents();
            } catch (error) {
                showMessage(error.message, 'error');
            }
        }

        function selectEvent(eventId) {
            currentEvent = events.find(e => e.id === eventId);
            document.getElementById('event-select').value = eventId;
            showGiftSection();
            loadGifts();
            connectToEvent(eventId);
        }

        function showGiftSection() {
            document.getElementById('gift-section').classList.remove('hidden');
        }

        // 礼金管理
        async function loadGifts() {
            if (!currentEvent) return;
            
            try {
                const gifts = await apiCall(`/gifts/${currentEvent.id}`);
                renderGifts(gifts);
                updateStats(gifts);
            } catch (error) {
                showMessage('加载礼金记录失败', 'error');
            }
        }

        function renderGifts(gifts) {
            const container = document.getElementById('gifts-list');
            
            if (gifts.length === 0) {
                container.innerHTML = `
                    <div class="text-center text-gray-400 py-8">
                        <div class="text-4xl mb-2">📝</div>
                        <p>暂无礼金记录</p>
                    </div>
                `;
                return;
            }

            container.innerHTML = gifts.map(gift => `
                <div class="flex items-center justify-between p-4 border-b border-gray-100 hover:bg-gray-50 transition duration-200">
                    <div class="flex-1">
                        <div class="font-medium text-gray-800">${gift.name}</div>
                        <div class="text-sm text-gray-500">${gift.payment_method} • ${new Date(gift.created_at).toLocaleString()}</div>
                        ${gift.note ? `<div class="text-sm text-gray-600 mt-1">${gift.note}</div>` : ''}
                    </div>
                    <div class="text-lg font-bold text-red-600">${formatCurrency(gift.amount)}</div>
                </div>
            `).join('');
        }

        function updateStats(gifts) {
            const totalAmount = gifts.reduce((sum, gift) => sum + gift.amount, 0);
            const totalCount = gifts.length;
            
            document.getElementById('total-amount').textContent = formatCurrency(totalAmount);
            document.getElementById('total-count').textContent = totalCount;
        }

        async function submitGift(giftData) {
            try {
                await apiCall('/gifts', {
                    method: 'POST',
                    body: JSON.stringify({
                        event_id: currentEvent.id,
                        ...giftData
                    })
                });
                
                showMessage('礼金录入成功', 'success');
                document.getElementById('gift-form').reset();
                loadGifts();
            } catch (error) {
                showMessage(error.message, 'error');
            }
        }

        // Socket连接
        function connectToEvent(eventId) {
            if (socket) {
                socket.disconnect();
            }
            
            socket = io();
            socket.emit('join_event', eventId);
            
            socket.on('gift_added', (data) => {
                if (data.event_id === currentEvent.id) {
                    loadGifts();
                }
            });
        }

        // 模态框管理
        function showCreateEventModal() {
            document.getElementById('create-event-modal').classList.remove('hidden');
        }

        function closeCreateEventModal() {
            document.getElementById('create-event-modal').classList.add('hidden');
            document.getElementById('create-event-form').reset();
        }

        // 事件监听器
        document.addEventListener('DOMContentLoaded', function() {
            // 检查是否已登录
            const token = localStorage.getItem('token');
            const user = localStorage.getItem('user');
            
            if (token && user) {
                currentUser = JSON.parse(user);
                showMainApp();
                loadEvents();
            } else {
                showLoginPage();
            }

            // 登录表单
            document.getElementById('login-form').addEventListener('submit', function(e) {
                e.preventDefault();
                const username = document.getElementById('username').value;
                const password = document.getElementById('password').value;
                login(username, password);
            });

            // 注册表单
            document.getElementById('register-form').addEventListener('submit', function(e) {
                e.preventDefault();
                const username = document.getElementById('reg-username').value;
                const password = document.getElementById('reg-password').value;
                register(username, password);
            });

            // 切换登录/注册
            document.getElementById('show-register').addEventListener('click', function() {
                document.getElementById('login-form').classList.add('hidden');
                document.getElementById('register-form').classList.remove('hidden');
            });

            document.getElementById('show-login').addEventListener('click', function() {
                document.getElementById('register-form').classList.add('hidden');
                document.getElementById('login-form').classList.remove('hidden');
            });

        // 礼金表单
        document.getElementById('gift-form').addEventListener('submit', function(e) {
            e.preventDefault();
            if (!currentEvent) {
                showMessage('请先选择一个活动', 'error');
                return;
            }
            
            const giftData = {
                name: document.getElementById('gift-name').value,
                amount: parseFloat(document.getElementById('gift-amount').value),
                payment_method: document.getElementById('gift-payment').value,
                note: document.getElementById('gift-note').value
            };
            
            submitGift(giftData);
        });

        // 多媒体上传表单
        document.getElementById('media-upload-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            if (!currentEvent) {
                showMessage('请先选择一个活动', 'error');
                return;
            }
            
            const fileInput = document.getElementById('media-file');
            const file = fileInput.files[0];
            
            if (!file) {
                showMessage('请选择要上传的文件', 'error');
                return;
            }
            
            const formData = new FormData();
            formData.append('file', file);
            formData.append('event_id', currentEvent.id);
            formData.append('type', document.getElementById('media-type').value);
            formData.append('title', document.getElementById('media-title').value);
            
            try {
                const token = localStorage.getItem('token');
                const response = await fetch('/api/media', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    body: formData
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    showMessage('多媒体文件上传成功', 'success');
                    document.getElementById('media-upload-form').reset();
                } else {
                    showMessage(data.error || '上传失败', 'error');
                }
            } catch (error) {
                showMessage('上传失败，请重试', 'error');
            }
        });

            // 创建活动表单
            document.getElementById('create-event-form').addEventListener('submit', function(e) {
                e.preventDefault();
                const eventData = {
                    title: document.getElementById('event-title').value,
                    description: document.getElementById('event-description').value,
                    event_date: document.getElementById('event-date').value,
                    theme: document.getElementById('event-theme').value
                };
                
                createEvent(eventData);
            });

            // 活动选择
            document.getElementById('event-select').addEventListener('change', function(e) {
                if (e.target.value) {
                    selectEvent(e.target.value);
                } else {
                    document.getElementById('gift-section').classList.add('hidden');
                }
            });

            // 按钮事件
            document.getElementById('create-event-btn').addEventListener('click', showCreateEventModal);
            document.getElementById('close-modal').addEventListener('click', closeCreateEventModal);
            document.getElementById('cancel-create').addEventListener('click', closeCreateEventModal);
            document.getElementById('logout-btn').addEventListener('click', logout);

            // 模态框点击外部关闭
            document.getElementById('create-event-modal').addEventListener('click', function(e) {
                if (e.target === this) {
                    closeCreateEventModal();
                }
            });
        });
    </script>
</body>
</html>
